package server;

import mapper.EasyHost;
import servlet.HttpServlet;

import java.net.Socket;
import java.util.List;
import java.util.Map;

/**
 * @author lbq
 * @version 1.0
 * @date 2021/1/22 22:06
 */
public class RequestProcessor implements Runnable {

    private Socket socket;
    private Map<String, HttpServlet> map;
    private Map<String, EasyHost> hostMap;

    // public RequestProcessor(Socket socket, Map<String, HttpServlet> map) {
    //     this.socket = socket;
    //     this.map = map;
    // }

    public RequestProcessor(Socket socket, Map<String, EasyHost> hostMap) {
        this.socket = socket;
        this.hostMap = hostMap;
    }

    @Override
    public void run() {
        try {
            Request request = new Request(socket.getInputStream());
            Response response = new Response(socket.getOutputStream());
            EasyHost localhost = hostMap.get("localhost");
            List<EasyHost.EasyContext> contexts = localhost.getContexts();
            for (EasyHost.EasyContext context : contexts) {
                String name = context.getName();
                if (!request.getUrl().startsWith("/" + name)) {
                    continue;
                }
                List<EasyHost.EasyWrapper> wrappers = context.getWrappers();
                for (EasyHost.EasyWrapper wrapper : wrappers) {
                    String url = wrapper.getUrl();
                    if (!request.getUrl().startsWith("/" + name + url)) {
                        continue;
                    }
                    HttpServlet servlet = wrapper.getServlet();
                    servlet.service(request, response);
                    break;
                }
            }
            if (request.getUrl().endsWith(".html") || request.getUrl().endsWith(".ico")) {
                response.outputHtml(request.getUrl());
            }
            // response.getOut().write(HttpProtocolUtil.getHttpHeader404().getBytes());
            // socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
